package com.ocom.common.utils;

import com.alibaba.fastjson.JSONArray;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author lu
 * @description
 * @date 2021年01月06日 10:52
 */
public class RequestConfig {

    /**
     * @author lu
     * @date 2021/1/7 17:07
     * @param: map
     * @param: req
     * @return boolean
     * @description 验证sign是否合法
    */
    public static boolean requestJSON(Map<String, Object> map,HttpServletRequest req){
        String Ts = req.getHeader("Ts");
        String Sign = req.getHeader("Sign");
        if (map==null){
            return false;
        }
        if (Ts==null || Sign==null){
            return false;
        }
        map.put("ts",Ts);
        SortedMap<String, Object> parameters = new TreeMap<String, Object>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if(JSONArray.class.isInstance(entry.getValue())) continue;
            String key=entry.getKey().toLowerCase();
            parameters.put(key,entry.getValue());
        }
        String strEncryption=createSign(parameters,"2D7E7C96-DAC5-4526-96C3-C60CDEC4B120");
        if (Sign.equals(strEncryption)){
            return true;
        }else {
            return false;
        }
    }

    /**
     * @author lu
     * @date 2021/1/8 9:08
     * @param: sessionId
     * @param: machNo
     * @param: req
     * @return boolean
     * @description 验证机器发送的令牌是否合法
    */
    public static boolean sessionIdTure(Map<String, Object> map,HttpServletRequest req){
        //获取随机数
        Object object = req.getSession().getAttribute(String.valueOf(map.get("machNo")));
        //根据机器号获取存到session的值
        String random= String.valueOf(object);

        //把加密获取到的session跟机器发过来的sessionId比对是否合法
        //机器传过来的sessionId
        String sessionId= String.valueOf(map.get("sessionId"));
        if (sessionId.equals(random)){
            return true;
        }
        return false;
    }

    /**
     * @author lu
     * @date 2021/1/6 14:52
     * @param: parameters
     * @return java.lang.String
     * @description 机器验签
     */
    public static String createSign(SortedMap<String,Object> parameters,String key){
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }

        sb=sb.append("key="+key);
//        System.out.println(sb);
        //MD5加密,结果转换为大写字符
        //String sign = MD5Util.MD5Encode(sbkey.toString(), characterEncoding).toUpperCase();
        String sign =MD5Util.stringToMD5(sb.toString());
//        System.out.println(sign);
        return sign;
    }
}
